//
//  CSYOAuthLoginViewController.swift
//  CSSinaMicroBlog_Test
//
//  Created by 姚彦兆 on 15/11/11.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

import UIKit

import AFNetworking

import SVProgressHUD

class CSYOAuthLoginViewController: UIViewController {

    
    var webView : UIWebView?
    
    
    func loadWebViewRequest(){
        
        //client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
    
        let urlSTR : String = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let requestURL = NSURL(string: urlSTR)
        
        let request : NSURLRequest = NSURLRequest(URL: requestURL!)
        
        webView?.loadRequest(request)
        
    }
    
    override func loadView() {
        
        super.loadView()
        
        webView = UIWebView()
        
        webView?.delegate = self
        
        self.view = webView
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAuthorize")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoInput")
        
        loadWebViewRequest()
        
        
    }
    
    @objc private func autoInput(){
    
        let js = "document.getElementById('userId').value = '18636706784';" + "document.getElementById('passwd').value = '15343577589Yyz';"
        
        webView!.stringByEvaluatingJavaScriptFromString(js)
    
    }
    
    func cancelAuthorize(){
    
        dismissViewControllerAnimated(true) { () -> Void in
            
            print("用户取消授权.....]]")
            
        }
    
    }

}

extension CSYOAuthLoginViewController : UIWebViewDelegate{


    func webViewDidStartLoad(webView: UIWebView) {
        
        print("WebView开始载入")
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        print("WebView载入完成")
        
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        print("WebView载入异常[手动中断] ---> \(error)")
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("截获网络请求 , 开始处理")
        
        print("\(request.URL)")
        
        guard let urlStr = request.URL?.absoluteString else{
        
            return false
        
        }
        
        if urlStr.hasPrefix("https://api.weibo.com/") {
        
            return true
        
        }
        
        if !urlStr.hasPrefix(redirect_uri) {
        
            print(urlStr)
            
            return false
        
        }
        
        guard let query = request.URL?.query else{
        
            return false
        
        }
        
        let codeSTR = "code="
        
        if let code : String = query.substringFromIndex(codeSTR.endIndex) {
        
        print("|||||| \(code) ||||||")
        
        CSYGetUserInfoModel().getUserInfoWithCode(code, finishBlock: { (errorMessage) -> () in
            
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                
                SVProgressHUD.dismiss()

            })
            
        })
        
        return true
        
    }

}


}